//
//  RegionViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/20.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "RegionViewController.h"

//Cell
#import "RegionHeadCell.h"
#import "RegionContentCell.h"

//Request
#import "HTTPPromise+Login.h"

//Model
#import "WXAuth2Model.h"

//Tools
#import "AppUtil.h"

@interface RegionViewController ()<UITableViewDelegate,UITableViewDataSource,RegionContentDelegate>
{
    int buttonOld;          //上次button的tag
    NSString *cityCode;           //城市code
}
@property (strong, nonatomic) IBOutlet UITableView *RegionTableView;
@property (strong, nonatomic) UIView *headerView;
@property (strong, nonatomic) NSMutableArray<Region2Model *> *dataArr;
@property (strong, nonatomic) Region2Model *paramModel;

@end

@implementation RegionViewController
#pragma mark -init
#define RegionHeadIdentifyCell @"RegionHeadCell"
#define RegionContentIdentifyCell @"RegionContentCell"

#pragma mark -懒加载
- (NSMutableArray<Region2Model *> *)dataArr
{
    if(!_dataArr)
    {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Xib
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([RegionHeadCell class])
                                bundle:[NSBundle mainBundle]];
    [_RegionTableView registerNib:nib forCellReuseIdentifier:RegionHeadIdentifyCell];
    
    UINib *nib1 = [UINib nibWithNibName:NSStringFromClass([RegionContentCell class])
                                bundle:[NSBundle mainBundle]];
    [_RegionTableView registerNib:nib1 forCellReuseIdentifier:RegionContentIdentifyCell];
    
    _dataArr = self.dataArr;
    buttonOld = 0;
    
    [self initTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"常驻城市"];
    
    [self initRequest];
}

- (void)initRequest
{
    NSDictionary *RegionrParam = @{};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:RegionrParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:RegionrParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestRegionAllParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        
        if (successRet == 0) {
            NSLog(@"%@",responseObj[@"info"]);
            NSArray *tempArr = [[NSArray alloc] initWithArray:responseObj[@"list"]];
            if(tempArr.count > 0)
            {
                for (int i = 0; i <tempArr.count; i++) {
                    Region2Model * model = [[Region2Model alloc] init];
                    [model setValuesForKeysWithDictionary:tempArr[i]];
                    [strongSelf->_dataArr addObject:model];
                }
                [strongSelf.RegionTableView reloadData];
            }
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)initTableView
{
    _RegionTableView.tableFooterView = [[UIView alloc] init];
    _RegionTableView.tableHeaderView = self.headerView;
    _RegionTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark -RegionDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(_dataArr != nil && _dataArr.count > 0){
        return 2;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        return 1;
    }else{
        if(_dataArr != nil && _dataArr.count > 0){
            if (_dataArr.count % 3 == 0) {
                return _dataArr.count / 3;
            }
            return _dataArr.count / 3 + 1;
        }
    }
    
    return 0;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        RegionHeadCell *regionHeadCell = [tableView dequeueReusableCellWithIdentifier:RegionHeadIdentifyCell];
        if(_paramModel != nil){
            [regionHeadCell configureCell:_paramModel.name];
        }
        
        regionHeadCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return regionHeadCell;
    }else if (indexPath.section == 1)
    {
        RegionContentCell *regionContentCell = [tableView dequeueReusableCellWithIdentifier:RegionContentIdentifyCell];
        regionContentCell.delegate = self;
        [regionContentCell configureCell:_dataArr AtWithIndex:indexPath.row AtWithSelectModel:_paramModel];
        
        regionContentCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return regionContentCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
    return headerView;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
    headerView.textLabel.font = [UIFont systemFontOfSize:15];
    
    if (section == 0) {
        headerView.textLabel.text = @"当前位置";
    }else{
        headerView.textLabel.text = @"国内其它地区";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if(indexPath.row == 0)
        {
            return 50;
        }
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if(indexPath.row == 0)
        {
            return 50;
        }
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    return 40;
}

#pragma mark -RegionContentDelegate
- (void)transmitTag:(int)buttonIndex{
    NSLog(@"%d",buttonIndex);
    
    if(_paramModel != nil){
        int tempId = [_paramModel.rId intValue];
        for (int i =0; i<_dataArr.count; i++) {
            Region2Model *tempRegion = [[Region2Model alloc] init];
            tempRegion = _dataArr[i];
            if ([tempRegion.rId intValue] == tempId) {
                buttonOld = 200 + i;
            }
        }
        
        NSLog(@"buttonOld:%d",buttonOld);
    }else{
        buttonOld = 0;
    }
    
    Region2Model *model = [[Region2Model alloc] init];
    model = _dataArr[buttonIndex - 200];
    
    UILabel *label = (UILabel *)[_RegionTableView viewWithTag:(666)];
    label.text = model.name;
    cityCode = model.rId;
    
    if(buttonOld != buttonIndex){
        if(buttonOld != 0 && buttonOld >= 200){
            UIButton *button = (UIButton *)[_RegionTableView viewWithTag:(buttonOld)];
            button.selected = NO;
            [button setBackgroundColor:[UIColor whiteColor]];
        }
        buttonOld = buttonIndex;
        
        UIButton *button1 = (UIButton *)[_RegionTableView viewWithTag:(buttonOld)];
        button1.selected = YES;
        [button1 setBackgroundColor:HTCFQuickRGBColor(32,170,255)];
        
        [self saveCityParams:model];
    }
}

- (void)saveCityParams:(Region2Model *)model{
    if(!HTCFStringIsNull(cityCode)){
        return ;
    }
    NSDictionary *regionParam = @{@"region":cityCode};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:regionParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:regionParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestUserRegionParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObj:%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        
        if (successRet == 0) {
            [strongSelf skipController:model];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController:(Region2Model *)model
{
    if ([_citydelegate respondsToSelector:@selector(transmitCity:)]) {
        [_citydelegate performSelector:@selector(transmitCity:) withObject:model];
    }
    
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)backAction:(UITapGestureRecognizer *)sender {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
